<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小鬼消消乐</title>
    <link rel="stylesheet" href="styles/main.css">
</head>

<body>
    <div class="game-container">
        <header class="game-header">
            <h1>小鬼消消乐</h1>
            <div class="game-info">
                <div class="score-display">
                    <span class="label">分数:</span>
                    <span id="score">0</span>
                </div>
                <div class="time-display">
                    <span class="label">时间:</span>
                    <span id="time">00:00</span>
                </div>
                <button id="restart-btn" class="restart-btn">重新开始</button>
            </div>
        </header>

        <main class="game-main">
            <div id="game-grid" class="game-grid">
                <!-- 游戏网格将通过JavaScript动态生成 -->
            </div>
        </main>

        <div class="game-overlay" id="game-overlay" style="display: none;">
            <div class="overlay-content">
                <h2 id="overlay-title">游戏暂停</h2>
                <p id="overlay-message">点击继续按钮恢复游戏</p>
                <button id="continue-btn" class="continue-btn">继续游戏</button>
            </div>
        </div>
    </div>

    <!-- 内联所有JavaScript代码以避免CORS问题 -->
    <script>
        // 游戏状态枚举
        const GameStatus = {
            INITIALIZING: 'INITIALIZING',
            READY: 'READY',
            PLAYING: 'PLAYING',
            SWAPPING: 'SWAPPING',
            MATCHING: 'MATCHING',
            FALLING: 'FALLING',
            PAUSED: 'PAUSED',
            GAME_OVER: 'GAME_OVER'
        };

        // 游戏网格数据模型
        class GameBoard {
            constructor(width = 8, height = 8) {
                this.width = width;
                this.height = height;
                this.grid = [];
                this.initializeGrid();
            }

            // 初始化8x8网格
            initializeGrid() {
                this.grid = [];
                for (let x = 0; x < this.width; x++) {
                    this.grid[x] = [];
                    for (let y = 0; y < this.height; y++) {
                        this.grid[x][y] = this.createCell(x, y, 0);
                    }
                }
                // 填充随机小鬼类型，确保无初始匹配
                this.fillGridWithoutMatches();
            }

            // 创建单元格数据模型
            createCell(x, y, type) {
                return {
                    type: type,           // 小鬼类型 (0-4)
                    id: `cell-${x}-${y}`, // 唯一标识符
                    x: x,                 // 网格X坐标
                    y: y,                 // 网格Y坐标
                    element: null         // DOM元素引用，稍后设置
                };
            }

            // 获取指定位置的单元格
            getCell(x, y) {
                if (this.isValidPosition(x, y)) {
                    return this.grid[x][y];
                }
                return null;
            }

            // 设置指定位置的单元格
            setCell(x, y, cell) {
                if (this.isValidPosition(x, y)) {
                    this.grid[x][y] = cell;
                    return true;
                }
                return false;
            }

            // 设置指定位置的小鬼类型
            setCellType(x, y, type) {
                const cell = this.getCell(x, y);
                if (cell) {
                    cell.type = type;
                    return true;
                }
                return false;
            }

            // 验证坐标是否有效
            isValidPosition(x, y) {
                return x >= 0 && x < this.width && y >= 0 && y < this.height;
            }

            // 交换两个单元格的位置
            swapCells(pos1, pos2) {
                const cell1 = this.getCell(pos1.x, pos1.y);
                const cell2 = this.getCell(pos2.x, pos2.y);

                if (cell1 && cell2) {
                    // 交换类型
                    const tempType = cell1.type;
                    cell1.type = cell2.type;
                    cell2.type = tempType;
                    return true;
                }
                return false;
            }

            // 检查两个位置是否相邻
            areAdjacent(pos1, pos2) {
                const dx = Math.abs(pos1.x - pos2.x);
                const dy = Math.abs(pos1.y - pos2.y);
                return (dx === 1 && dy === 0) || (dx === 0 && dy === 1);
            }

            // 生成随机小鬼类型 (0-4，共5种类型)
            getRandomGhostType() {
                return Math.floor(Math.random() * 5);
            }

            // 获取安全的随机类型（避免在指定位置产生匹配）
            getSafeRandomType(x, y) {
                const forbiddenTypes = new Set();

                // 检查水平方向的潜在匹配
                const leftTypes = [];
                for (let i = x - 1; i >= Math.max(0, x - 2); i--) {
                    const cell = this.getCell(i, y);
                    if (cell && cell.type >= 0) {
                        leftTypes.push(cell.type);
                    } else {
                        break;
                    }
                }

                // 如果左边有两个相同类型，禁用该类型
                if (leftTypes.length >= 2 && leftTypes[0] === leftTypes[1]) {
                    forbiddenTypes.add(leftTypes[0]);
                }

                // 检查垂直方向的潜在匹配
                const upTypes = [];
                for (let i = y - 1; i >= Math.max(0, y - 2); i--) {
                    const cell = this.getCell(x, i);
                    if (cell && cell.type >= 0) {
                        upTypes.push(cell.type);
                    } else {
                        break;
                    }
                }

                // 如果上面有两个相同类型，禁用该类型
                if (upTypes.length >= 2 && upTypes[0] === upTypes[1]) {
                    forbiddenTypes.add(upTypes[0]);
                }

                // 生成不在禁用列表中的随机类型
                let type;
                let attempts = 0;
                do {
                    type = this.getRandomGhostType();
                    attempts++;
                    // 防止无限循环
                    if (attempts > 20) {
                        break;
                    }
                } while (forbiddenTypes.has(type) && forbiddenTypes.size < 5);

                return type;
            }

            // 填充网格，确保无初始匹配
            fillGridWithoutMatches() {
                for (let y = 0; y < this.height; y++) {
                    for (let x = 0; x < this.width; x++) {
                        const safeType = this.getSafeRandomType(x, y);
                        this.setCellType(x, y, safeType);
                    }
                }
            }

            // 重新生成网格
            regenerateGrid() {
                this.initializeGrid();
            }

            // 查找所有匹配
            findMatches() {
                const matches = [];
                const horizontalMatches = this.findHorizontalMatches();
                const verticalMatches = this.findVerticalMatches();

                matches.push(...horizontalMatches);
                matches.push(...verticalMatches);

                return this.mergeOverlappingMatches(matches);
            }

            // 查找水平匹配
            findHorizontalMatches() {
                const matches = [];

                for (let y = 0; y < this.height; y++) {
                    let count = 1;
                    let currentType = this.grid[0][y].type;
                    let startX = 0;

                    for (let x = 1; x < this.width; x++) {
                        const cellType = this.grid[x][y].type;

                        if (cellType === currentType && cellType >= 0) {
                            count++;
                        } else {
                            // 检查是否形成匹配（3个或更多）
                            if (count >= 3 && currentType >= 0) {
                                matches.push(this.createMatch(startX, y, count, 'horizontal', currentType));
                            }

                            // 重置计数
                            count = 1;
                            currentType = cellType;
                            startX = x;
                        }
                    }

                    // 检查行末尾的匹配
                    if (count >= 3 && currentType >= 0) {
                        matches.push(this.createMatch(startX, y, count, 'horizontal', currentType));
                    }
                }

                return matches;
            }

            // 查找垂直匹配
            findVerticalMatches() {
                const matches = [];

                for (let x = 0; x < this.width; x++) {
                    let count = 1;
                    let currentType = this.grid[x][0].type;
                    let startY = 0;

                    for (let y = 1; y < this.height; y++) {
                        const cellType = this.grid[x][y].type;

                        if (cellType === currentType && cellType >= 0) {
                            count++;
                        } else {
                            // 检查是否形成匹配（3个或更多）
                            if (count >= 3 && currentType >= 0) {
                                matches.push(this.createMatch(x, startY, count, 'vertical', currentType));
                            }

                            // 重置计数
                            count = 1;
                            currentType = cellType;
                            startY = y;
                        }
                    }

                    // 检查列末尾的匹配
                    if (count >= 3 && currentType >= 0) {
                        matches.push(this.createMatch(x, startY, count, 'vertical', currentType));
                    }
                }

                return matches;
            }

            // 创建匹配对象
            createMatch(startX, startY, length, direction, type) {
                const cells = [];

                if (direction === 'horizontal') {
                    for (let i = 0; i < length; i++) {
                        cells.push({ x: startX + i, y: startY });
                    }
                } else { // vertical
                    for (let i = 0; i < length; i++) {
                        cells.push({ x: startX, y: startY + i });
                    }
                }

                return {
                    cells: cells,
                    type: type,
                    direction: direction,
                    length: length
                };
            }

            // 合并重叠的匹配
            mergeOverlappingMatches(matches) {
                if (matches.length <= 1) return matches;

                const cellsToRemove = new Set();

                // 收集所有需要移除的单元格
                matches.forEach(match => {
                    match.cells.forEach(cell => {
                        cellsToRemove.add(`${cell.x},${cell.y}`);
                    });
                });

                // 创建合并后的匹配对象
                const mergedCells = Array.from(cellsToRemove).map(cellStr => {
                    const [x, y] = cellStr.split(',').map(Number);
                    return { x, y };
                });

                if (mergedCells.length >= 3) {
                    return [{
                        cells: mergedCells,
                        type: matches[0].type, // 使用第一个匹配的类型
                        direction: 'mixed',
                        length: mergedCells.length
                    }];
                }

                return matches;
            }

            // 移除匹配的单元格
            removeMatches(matches) {
                const removedCells = [];

                matches.forEach(match => {
                    match.cells.forEach(cell => {
                        if (this.getCell(cell.x, cell.y)) {
                            this.clearCell(cell.x, cell.y);
                            removedCells.push(cell);
                        }
                    });
                });

                return removedCells;
            }

            // 清空指定位置的单元格
            clearCell(x, y) {
                const cell = this.getCell(x, y);
                if (cell) {
                    cell.type = -1; // -1 表示空单元格
                    return true;
                }
                return false;
            }

            // 检查单元格是否为空
            isEmpty(x, y) {
                const cell = this.getCell(x, y);
                return cell && cell.type === -1;
            }

            // 检查交换是否有效（会产生匹配）
            isValidSwap(pos1, pos2) {
                // 检查是否相邻
                if (!this.areAdjacent(pos1, pos2)) {
                    return false;
                }

                // 临时交换
                this.swapCells(pos1, pos2);

                // 检查是否产生匹配
                const matches = this.findMatches();
                const hasMatches = matches.length > 0;

                // 恢复交换
                this.swapCells(pos1, pos2);

                return hasMatches;
            }

            // 应用重力效果
            applyGravity() {
                const moves = [];

                for (let x = 0; x < this.width; x++) {
                    let writeIndex = this.height - 1;

                    // 从底部向上扫描
                    for (let y = this.height - 1; y >= 0; y--) {
                        const cell = this.getCell(x, y);
                        if (cell && cell.type >= 0) {
                            if (y !== writeIndex) {
                                // 记录移动
                                moves.push({
                                    from: { x, y },
                                    to: { x, y: writeIndex }
                                });

                                // 移动单元格
                                this.setCellType(x, writeIndex, cell.type);
                                this.clearCell(x, y);
                            }
                            writeIndex--;
                        }
                    }
                }

                return moves;
            }

            // 填充空单元格
            fillEmptySpaces() {
                const newCells = [];

                for (let x = 0; x < this.width; x++) {
                    // 应用重力，让非空单元格下落
                    const column = [];
                    for (let y = this.height - 1; y >= 0; y--) {
                        const cell = this.getCell(x, y);
                        if (cell && cell.type >= 0) {
                            column.push(cell.type);
                        }
                    }

                    // 填充列
                    let writeIndex = this.height - 1;

                    // 先放置现有的非空单元格
                    for (let i = 0; i < column.length; i++) {
                        this.setCellType(x, writeIndex, column[i]);
                        writeIndex--;
                    }

                    // 在顶部生成新的随机单元格
                    while (writeIndex >= 0) {
                        const newType = this.getSafeRandomType(x, writeIndex);
                        this.setCellType(x, writeIndex, newType);
                        newCells.push({ x, y: writeIndex, type: newType });
                        writeIndex--;
                    }
                }

                return newCells;
            }
        }

        // 游戏渲染器
        class GameRenderer {
            constructor(container) {
                this.container = container;
                this.gridElement = null;
                this.cellElements = [];
            }

            // 创建8x8游戏网格的DOM结构
            createGrid() {
                // 获取游戏网格容器
                this.gridElement = this.container.querySelector('#game-grid');

                if (!this.gridElement) {
                    console.error('找不到游戏网格容器');
                    return;
                }

                // 清空现有内容
                this.gridElement.innerHTML = '';

                // 初始化单元格元素数组
                this.cellElements = [];
                for (let x = 0; x < 8; x++) {
                    this.cellElements[x] = [];
                }

                // 创建64个单元格元素
                for (let y = 0; y < 8; y++) {
                    for (let x = 0; x < 8; x++) {
                        const cellElement = this.createCellElement(x, y);
                        this.gridElement.appendChild(cellElement);
                        this.cellElements[x][y] = cellElement;
                    }
                }

                console.log('游戏网格DOM创建完成');
            }

            // 创建单个单元格元素
            createCellElement(x, y) {
                const cellDiv = document.createElement('div');
                cellDiv.className = 'ghost-cell';
                cellDiv.dataset.x = x;
                cellDiv.dataset.y = y;
                cellDiv.id = `cell-${x}-${y}`;

                // 创建小鬼图标容器
                const ghostIcon = document.createElement('div');
                ghostIcon.className = 'ghost-icon';
                cellDiv.appendChild(ghostIcon);

                return cellDiv;
            }

            // 渲染单个单元格
            renderCell(cell, x, y) {
                const cellElement = this.getCellElement(x, y);
                if (!cellElement) {
                    console.error(`找不到单元格元素 (${x}, ${y})`);
                    return;
                }

                const ghostIcon = cellElement.querySelector('.ghost-icon');
                if (!ghostIcon) {
                    console.error(`找不到小鬼图标元素 (${x}, ${y})`);
                    return;
                }

                // 移除所有类型样式
                for (let i = 0; i < 5; i++) {
                    ghostIcon.classList.remove(`ghost-type-${i}`);
                }

                // 根据单元格类型设置样式
                if (cell.type >= 0 && cell.type <= 4) {
                    ghostIcon.classList.add(`ghost-type-${cell.type}`);
                    ghostIcon.textContent = this.getGhostEmoji(cell.type);
                    cellElement.style.opacity = '1';
                } else {
                    // 空单元格
                    ghostIcon.textContent = '';
                    cellElement.style.opacity = '0.3';
                }

                // 更新单元格的DOM元素引用
                cell.element = cellElement;
            }

            // 获取小鬼表情符号
            getGhostEmoji(type) {
                const emojis = ['👻', '🎃', '💀', '🦇', '🕷️'];
                return emojis[type] || '👻';
            }

            // 获取指定位置的单元格元素
            getCellElement(x, y) {
                if (x >= 0 && x < 8 && y >= 0 && y < 8 && this.cellElements[x]) {
                    return this.cellElements[x][y];
                }
                return null;
            }

            // 渲染整个网格
            renderGrid(gameBoard) {
                for (let x = 0; x < 8; x++) {
                    for (let y = 0; y < 8; y++) {
                        const cell = gameBoard.getCell(x, y);
                        if (cell) {
                            this.renderCell(cell, x, y);
                        }
                    }
                }
            }

            // 高亮显示单元格
            highlightCell(x, y) {
                const cellElement = this.getCellElement(x, y);
                if (cellElement) {
                    cellElement.classList.add('selected');
                }
            }

            // 移除所有高亮
            removeHighlight() {
                const selectedCells = this.gridElement.querySelectorAll('.ghost-cell.selected');
                selectedCells.forEach(cell => {
                    cell.classList.remove('selected');
                });
            }

            // 移除指定单元格的高亮
            removeHighlightFromCell(x, y) {
                const cellElement = this.getCellElement(x, y);
                if (cellElement) {
                    cellElement.classList.remove('selected');
                }
            }

            // 更新分数显示
            updateScore(score) {
                const scoreElement = this.container.querySelector('#score');
                if (scoreElement) {
                    scoreElement.textContent = score.toLocaleString();

                    // 添加分数更新动画
                    scoreElement.classList.add('score-update');
                    setTimeout(() => {
                        scoreElement.classList.remove('score-update');
                    }, 300);
                }
            }

            // 更新时间显示
            updateTimer(timeInSeconds) {
                const timeElement = this.container.querySelector('#time');
                if (timeElement) {
                    const minutes = Math.floor(timeInSeconds / 60);
                    const seconds = timeInSeconds % 60;
                    const formattedTime = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                    timeElement.textContent = formattedTime;
                }
            }

            // 获取单元格位置（从DOM元素）
            getCellPosition(element) {
                const x = parseInt(element.dataset.x);
                const y = parseInt(element.dataset.y);

                if (isNaN(x) || isNaN(y)) {
                    return null;
                }

                return { x, y };
            }

            // 显示状态消息
            showStatusMessage(message, duration = 2000) {
                // 创建状态消息元素
                let statusElement = this.container.querySelector('.status-message');

                if (!statusElement) {
                    statusElement = document.createElement('div');
                    statusElement.className = 'status-message';
                    this.container.appendChild(statusElement);
                }

                statusElement.textContent = message;
                statusElement.style.display = 'block';
                statusElement.classList.add('show');

                // 自动隐藏消息
                setTimeout(() => {
                    statusElement.classList.remove('show');
                    setTimeout(() => {
                        statusElement.style.display = 'none';
                    }, 300);
                }, duration);
            }
        }

        // 分数管理器
        class ScoreManager {
            constructor() {
                this.score = 0;
                this.time = 0;
                this.timer = null;
                this.timerCallback = null;
                this.isPaused = false;
                this.startTime = null;
                this.pausedTime = 0;
            }

            // 计算分数
            calculateScore(matchLength, combo = 1) {
                // 基础分数：每个消除的小鬼10分
                let baseScore = matchLength * 10;

                // 长度奖励：超过3个的额外奖励
                if (matchLength > 3) {
                    baseScore += (matchLength - 3) * 20;
                }

                // 连击倍数
                let comboMultiplier = 1;
                if (combo > 1) {
                    comboMultiplier = 1 + (combo - 1) * 0.5; // 每次连击增加50%
                }

                // 计算最终分数
                const finalScore = Math.floor(baseScore * comboMultiplier);

                console.log(`分数计算: 基础${baseScore} × 连击${comboMultiplier.toFixed(1)} = ${finalScore}`);

                return finalScore;
            }

            // 开始计时
            startTimer(callback) {
                this.timerCallback = callback;
                this.startTime = Date.now();
                this.time = 0;
                this.pausedTime = 0;
                this.isPaused = false;

                this.timer = setInterval(() => {
                    if (!this.isPaused) {
                        const elapsed = Math.floor((Date.now() - this.startTime - this.pausedTime) / 1000);
                        this.time = elapsed;

                        if (this.timerCallback) {
                            this.timerCallback(this.time);
                        }
                    }
                }, 1000);

                console.log('计时器开始');
            }

            // 停止计时
            stopTimer() {
                if (this.timer) {
                    clearInterval(this.timer);
                    this.timer = null;
                    this.timerCallback = null;
                    console.log('计时器停止');
                }
            }

            // 重置分数管理器
            reset() {
                this.stopTimer();
                this.score = 0;
                this.time = 0;
                this.isPaused = false;
                this.startTime = null;
                this.pausedTime = 0;
                console.log('分数管理器重置');
            }
        }

        // 输入处理器
        class InputHandler {
            constructor(gameEngine) {
                this.gameEngine = gameEngine;
                this.selectedCell = null;
                this.isProcessing = false;
            }

            // 绑定所有输入事件
            bindEvents() {
                // 绑定单元格点击事件
                if (this.gameEngine.renderer.gridElement) {
                    this.gameEngine.renderer.gridElement.addEventListener('click', (event) => {
                        const cellElement = event.target.closest('.ghost-cell');
                        if (cellElement) {
                            const position = this.gameEngine.renderer.getCellPosition(cellElement);
                            if (position) {
                                this.handleCellClick(position, cellElement);
                            }
                        }
                    });
                }

                // 绑定重新开始按钮
                const restartBtn = this.gameEngine.renderer.container.querySelector('#restart-btn');
                if (restartBtn) {
                    restartBtn.addEventListener('click', () => {
                        this.gameEngine.reset();
                    });
                }

                console.log('输入事件绑定完成');
            }

            // 处理单元格点击事件
            handleCellClick(position, element) {
                console.log(`点击单元格 (${position.x}, ${position.y}), isProcessing=${this.isProcessing}`);

                // 防止在处理过程中重复点击
                if (this.isProcessing) {
                    console.log('正在处理中，忽略点击');
                    return;
                }

                // 检查游戏状态
                if (!this.gameEngine.canInteract()) {
                    console.log('游戏无法交互，忽略点击');
                    return;
                }

                const { x, y } = position;

                // 如果没有选中的单元格，选中当前单元格
                if (!this.selectedCell) {
                    this.selectCell(x, y);
                } else {
                    // 如果点击的是已选中的单元格，取消选择
                    if (this.selectedCell.x === x && this.selectedCell.y === y) {
                        this.deselectCell();
                    } else {
                        // 尝试交换单元格
                        this.attemptSwap(this.selectedCell, { x, y });
                    }
                }
            }

            // 选中单元格
            selectCell(x, y) {
                const cell = this.gameEngine.gameBoard.getCell(x, y);

                if (!cell || cell.type < 0) {
                    return; // 不能选中空单元格
                }

                // 清除之前的选择
                this.deselectCell();

                // 选中新单元格
                this.selectedCell = { x, y };
                this.gameEngine.renderer.highlightCell(x, y);

                console.log(`选中单元格 (${x}, ${y})`);
            }

            // 取消选中单元格
            deselectCell() {
                if (this.selectedCell) {
                    this.gameEngine.renderer.removeHighlightFromCell(this.selectedCell.x, this.selectedCell.y);
                    this.selectedCell = null;
                    console.log('取消选择');
                }
            }

            // 尝试交换单元格
            async attemptSwap(pos1, pos2) {
                this.isProcessing = true;

                try {
                    // 检查是否相邻
                    if (!this.isValidSelection(pos1, pos2)) {
                        // 如果不相邻，选中新的单元格
                        this.selectCell(pos2.x, pos2.y);
                        this.isProcessing = false;
                        return;
                    }

                    // 检查交换是否有效（会产生匹配）
                    if (!this.gameEngine.gameBoard.isValidSwap(pos1, pos2)) {
                        // 无效交换，显示提示并保持选择
                        this.gameEngine.renderer.showStatusMessage('无效的交换！', 1000);
                        this.isProcessing = false;
                        return;
                    }

                    // 执行交换
                    console.log(`交换单元格 (${pos1.x}, ${pos1.y}) 和 (${pos2.x}, ${pos2.y})`);

                    // 清除选择状态
                    this.deselectCell();

                    // 通知游戏引擎处理交换
                    await this.gameEngine.handleSwap(pos1, pos2);

                } catch (error) {
                    console.error('交换操作失败:', error);
                } finally {
                    this.isProcessing = false;
                }
            }

            // 验证选择是否有效
            isValidSelection(pos1, pos2) {
                // 检查坐标是否有效
                if (!this.gameEngine.gameBoard.isValidPosition(pos1.x, pos1.y) ||
                    !this.gameEngine.gameBoard.isValidPosition(pos2.x, pos2.y)) {
                    return false;
                }

                // 检查是否相邻
                return this.gameEngine.gameBoard.areAdjacent(pos1, pos2);
            }

            // 重置输入处理器
            reset() {
                this.deselectCell();
                this.isProcessing = false;
            }
        }

        // 游戏引擎主控制器
        class GameEngine {
            constructor(containerElement) {
                this.container = containerElement;

                // 初始化游戏状态
                this.gameState = {
                    status: GameStatus.INITIALIZING,
                    score: 0,
                    time: 0,
                    combo: 0,
                    isAnimating: false
                };

                // 初始化各个模块
                this.gameBoard = null;
                this.renderer = null;
                this.inputHandler = null;
                this.scoreManager = null;
            }

            // 初始化游戏
            async init() {
                console.log('游戏引擎初始化中...');

                try {
                    // 创建游戏模块
                    this.gameBoard = new GameBoard(8, 8);
                    this.renderer = new GameRenderer(this.container);
                    this.inputHandler = new InputHandler(this);
                    this.scoreManager = new ScoreManager();

                    // 创建游戏网格DOM
                    this.renderer.createGrid();

                    // 渲染初始网格
                    this.renderer.renderGrid(this.gameBoard);

                    // 绑定事件
                    this.inputHandler.bindEvents();

                    // 初始化UI
                    this.renderer.updateScore(this.gameState.score);
                    this.renderer.updateTimer(this.gameState.time);

                    // 设置状态为就绪
                    this.gameState.status = GameStatus.READY;

                    console.log('游戏引擎初始化完成');

                } catch (error) {
                    console.error('游戏初始化失败:', error);
                    this.gameState.status = GameStatus.GAME_OVER;
                }
            }

            // 开始游戏
            start() {
                if (this.gameState.status !== GameStatus.READY) {
                    console.warn('游戏未就绪，无法开始');
                    return;
                }

                console.log('游戏开始');
                this.gameState.status = GameStatus.PLAYING;

                // 开始计时
                this.scoreManager.startTimer((time) => {
                    this.gameState.time = time;
                    this.renderer.updateTimer(time);
                });
            }

            // 重置游戏
            reset() {
                console.log('游戏重置');

                // 重置游戏状态
                this.gameState = {
                    status: GameStatus.INITIALIZING,
                    score: 0,
                    time: 0,
                    combo: 0,
                    isAnimating: false
                };

                // 重置各个模块
                this.gameBoard.regenerateGrid();
                this.scoreManager.reset();
                this.inputHandler.reset();

                // 重新渲染
                this.renderer.renderGrid(this.gameBoard);
                this.renderer.updateScore(this.gameState.score);
                this.renderer.updateTimer(this.gameState.time);

                // 设置为就绪状态
                this.gameState.status = GameStatus.READY;

                // 自动开始游戏
                this.start();
            }

            // 处理交换操作
            async handleSwap(pos1, pos2) {
                if (this.gameState.status !== GameStatus.PLAYING || this.gameState.isAnimating) {
                    return;
                }

                this.gameState.status = GameStatus.SWAPPING;
                this.gameState.isAnimating = true;

                try {
                    // 在数据模型中执行交换
                    this.gameBoard.swapCells(pos1, pos2);

                    // 更新渲染
                    this.renderer.renderGrid(this.gameBoard);

                    // 检查并处理匹配
                    await this.processMatches();

                } catch (error) {
                    console.error('交换处理失败:', error);
                } finally {
                    this.gameState.isAnimating = false;
                    if (this.gameState.status === GameStatus.SWAPPING) {
                        this.gameState.status = GameStatus.PLAYING;
                    }
                }
            }

            // 检查匹配
            checkMatches() {
                return this.gameBoard.findMatches();
            }

            // 处理匹配
            async processMatches() {
                let totalMatches = 0;
                this.gameState.combo = 0;

                while (true) {
                    // 检查匹配
                    const matches = this.checkMatches();

                    if (matches.length === 0) {
                        break; // 没有更多匹配
                    }

                    this.gameState.status = GameStatus.MATCHING;
                    this.gameState.combo++;
                    totalMatches += matches.length;

                    // 移除匹配的单元格
                    const removedCells = this.gameBoard.removeMatches(matches);

                    // 计算分数
                    const points = this.scoreManager.calculateScore(removedCells.length, this.gameState.combo);
                    this.gameState.score += points;
                    this.renderer.updateScore(this.gameState.score);

                    // 显示连击效果
                    if (this.gameState.combo > 1) {
                        this.renderer.showStatusMessage(`连击 x${this.gameState.combo}!`, 1500);
                    }

                    // 应用重力
                    await this.applyGravity();

                    // 填充新单元格
                    const newCells = this.gameBoard.fillEmptySpaces();

                    if (newCells.length > 0) {
                        // 更新渲染
                        this.renderer.renderGrid(this.gameBoard);
                    }

                    // 简单延迟以便观察效果
                    await new Promise(resolve => setTimeout(resolve, 300));
                }

                // 重置连击
                this.gameState.combo = 0;

                // 恢复游戏状态为可交互
                this.gameState.status = GameStatus.PLAYING;
            }

            // 应用重力效果
            async applyGravity() {
                this.gameState.status = GameStatus.FALLING;

                // 计算重力移动
                const moves = this.gameBoard.applyGravity();

                if (moves.length > 0) {
                    // 更新渲染
                    this.renderer.renderGrid(this.gameBoard);
                }
            }

            // 检查是否可以交互
            canInteract() {
                const canInteract = this.gameState.status === GameStatus.PLAYING && !this.gameState.isAnimating;
                console.log(`游戏交互状态: status=${this.gameState.status}, isAnimating=${this.gameState.isAnimating}, canInteract=${canInteract}`);
                return canInteract;
            }

            // 获取游戏状态
            getGameState() {
                return { ...this.gameState };
            }
        }

        // 游戏初始化
        document.addEventListener('DOMContentLoaded', async () => {
            try {
                const gameContainer = document.querySelector('.game-container');
                const game = new GameEngine(gameContainer);

                await game.init();
                game.start();

                window.game = game;
                console.log('游戏加载完成！');

            } catch (error) {
                console.error('游戏加载失败:', error);
            }
        });
    </script>
</body>

</html>